package com.dunshan.prcexp.util;

import com.alibaba.fastjson.JSON;
import com.dunshan.prcexp.base.CommonResponse;
import com.dunshan.prcexp.pojo.HttpEntity;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author liwen406
 * @program: dunshan-pef
 * @description:
 * @date 2022-08-25 11:11:04
 */
public class OkHttpUtils {
    private static OkHttpClient okHttpClient;

    public OkHttpUtils() {
    }

    public static CommonResponse<String> call(Request request) {
        CommonResponse crs = new CommonResponse();

        try {
            Response response = okHttpClient.newCall(request).execute();
            Throwable var3 = null;

            try {
                crs.setSuccess(response.isSuccessful());
                crs.setData(((ResponseBody)Objects.requireNonNull(response.body())).string());
            } catch (Throwable var13) {
                var3 = var13;
                throw var13;
            } finally {
                if (response != null) {
                    if (var3 != null) {
                        try {
                            response.close();
                        } catch (Throwable var12) {
                            var3.addSuppressed(var12);
                        }
                    } else {
                        response.close();
                    }
                }

            }
        } catch (Exception var15) {
            crs.setSuccess(false);
            crs.setData(TextUtil.exceptionToString(var15));
        }

        return crs;
    }

    public static void enqueue(Request request) {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            }
        });
    }

    public static CommonResponse<Map<String, String>> defaultCall(Request request) {
        CommonResponse crs = new CommonResponse();

        try {
            Response response = okHttpClient.newCall(request).execute();
            Throwable var19 = null;

            try {
                crs.setSuccess(response.isSuccessful());
                Map<String, String> dataMap = new HashMap();
                dataMap.put("body", ((ResponseBody)Objects.requireNonNull(response.body())).string());
                Map<String, String> headersMap = new HashMap(1);
                Iterator var6 = response.headers().names().iterator();

                while(var6.hasNext()) {
                    String key = (String)var6.next();
                    headersMap.put(key, response.headers().get(key));
                }

                dataMap.put("headers", JSON.toJSONString(headersMap));
                crs.setData(dataMap);
            } catch (Throwable var16) {
                var19 = var16;
                throw var16;
            } finally {
                if (response != null) {
                    if (var19 != null) {
                        try {
                            response.close();
                        } catch (Throwable var15) {
                            var19.addSuppressed(var15);
                        }
                    } else {
                        response.close();
                    }
                }

            }
        } catch (Exception var18) {
            crs.setSuccess(false);
            Map<String, String> dataMap = new HashMap();
            dataMap.put("body", TextUtil.exceptionToString(var18));
            dataMap.put("headers", "");
            crs.setData(dataMap);
        }

        return crs;
    }

    public static Map<String, String> queryParamsWithSign(String url, Map<String, String> queryParams, String body) {
        HttpUrl httpUrl = HttpUrl.parse(url);
        Map<String, String> retQueryParams = new HashMap();
        Map<String, String> signQueryParams = new HashMap();
        Iterator var6;
        String key;
        if (httpUrl != null) {
            var6 = httpUrl.queryParameterNames().iterator();

            while(var6.hasNext()) {
                key = (String)var6.next();
                signQueryParams.put(key, httpUrl.queryParameter(key));
            }
        }

        if (queryParams != null && queryParams.size() > 0) {
            var6 = queryParams.keySet().iterator();

            while(var6.hasNext()) {
                key = (String)var6.next();
                signQueryParams.put(key, queryParams.get(key));
                retQueryParams.put(key, queryParams.get(key));
            }
        }

//        Map<String, String> signMap = GWSignUtils.getSign(signQueryParams, body);
//        Iterator var10 = signMap.keySet().iterator();

//        while(var10.hasNext()) {
//            String key = (String)var10.next();
//            retQueryParams.put(key, signMap.get(key));
//        }

        return retQueryParams;
    }

    public static HttpUrl getHttpUrl(HttpEntity httpEntity, boolean ipDirect) {
        HttpUrl url = HttpUrl.parse(httpEntity.getUrl());
        if (url != null && httpEntity.getParameter() != null && httpEntity.getParameter().size() > 0) {
            HttpUrl.Builder urlBuilder;
            if (ipDirect) {
                String ip = "127.0.0.1";
                if (!StringUtils.isEmpty(httpEntity.getIp())) {
                    ip = httpEntity.getIp().split(" ")[0];
                }

                urlBuilder = url.newBuilder().host(ip);
            } else {
                urlBuilder = url.newBuilder();
            }

            Iterator var9 = httpEntity.getParameter().keySet().iterator();

            while(var9.hasNext()) {
                String key = (String)var9.next();
                urlBuilder.addQueryParameter(key, httpEntity.getParameter().get(key).toString());
            }

            url = urlBuilder.build();
            if (httpEntity.isOnGate()) {
                Map<String, String> queryParams = new HashMap();
                Iterator var11 = url.queryParameterNames().iterator();

                while(var11.hasNext()) {
                    String key = (String)var11.next();
                    queryParams.put(key, url.queryParameter(key));
                }

//                Map<String, String> signMap = GWSignUtils.getSign(queryParams, httpEntity.getBody());
//                HttpUrl.Builder signBuilder = url.newBuilder();
//                Iterator var7 = signMap.keySet().iterator();

//                while(var7.hasNext()) {
//                    String key = (String)var7.next();
//                    signBuilder.addQueryParameter(key, (String)signMap.get(key));
//                }
//
//                url = signBuilder.build();
            }
        }

        return url;
    }

    public static Headers getManHeaders() {
        return (new okhttp3.Headers.Builder()).add("tag", "dhf2").add("token", "c50c23703532348ef837fb5859dcbdc6").add("timestamp", String.valueOf(System.currentTimeMillis())).build();
    }

    public static String encodeHeaderValue(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        } else if (";".equals(value.trim())) {
            return value;
        } else {
            StringBuffer sb = new StringBuffer(0);
            String[] var2 = value.trim().split(";");
            int var3 = var2.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                String val = var2[var4];
                String[] pairs = val.split("=");
                if (pairs.length != 2) {
                    sb.append(val).append(";");
                } else {
                    sb.append(pairs[0]).append("=");
                    if (TextUtil.isChinese(pairs[1])) {
                        sb.append(TextUtil.urlEncode(pairs[1]));
                    } else {
                        sb.append(pairs[1]);
                    }

                    sb.append(";");
                }
            }

            String str = sb.toString();
            if (str.length() > 0 && !";".equals(value.substring(value.length() - 1)) && ";".equals(str.substring(str.length() - 1))) {
                str = str.substring(0, str.length() - 1);
            }

            return str;
        }
    }

    static {
        okHttpClient = OkHttpUtils.OkHttpSingleton.INSTANCE.init();
    }

    private static enum OkHttpSingleton {
        INSTANCE;

        private final OkHttpClient ohc;

        private OkHttpSingleton() {
            List<Protocol> protocols = new ArrayList();
            protocols.add(Protocol.HTTP_1_1);
            protocols.add(Protocol.HTTP_2);
            this.ohc = (new OkHttpClient()).newBuilder().protocols(protocols).connectTimeout(60L, TimeUnit.SECONDS).readTimeout(60L, TimeUnit.SECONDS).writeTimeout(60L, TimeUnit.SECONDS).build();
        }

        public OkHttpClient init() {
            return this.ohc;
        }
    }
}
